package bookless.pakage;

import java.util.ArrayList;

import activities.LoginActivity;
import activities.NewUserActivity;

public class UserHandler {

	public static String session;

	public UserHandler() {

	}

	/**
	 * Checks that the input is valued, user exist and that the password is
	 * correct,
	 * 
	 * @param userName
	 *            unique name to tells how want to login
	 * @param password
	 *            must match the password in the database.
	 * @return String, tells if and what went wrong.
	 */
	public static String login(String userName, String password) {
		String response = null;
		if (!(userName.isEmpty() && password.isEmpty())) {
			if (StorageHandler.getUser(userName, LoginActivity.getContext())
					.getUserName().equals(userName)) {
				if (StorageHandler
						.getUser(userName, LoginActivity.getContext())
						.getPassword().equals(password)) {
					session = userName;
					response = "ok";
					return response;
				} else {
					response = "wrongPassword";
					return response;
				}
			} else {
				response = "noUser";
				return response;
			}
		} else {
			response = "wrongInData";
			return response;
		}
	}

	/**
	 * Checks so no user with the same user name already exist
	 * 
	 * @param userName
	 *            must be unique
	 * @param password
	 *            must be longer then 3 character
	 * @return String, tells if and what went wrong.
	 */
	public static String addUser(String userName, String password) {
		String response = null;

		if (!userName.isEmpty() && (password.length() > 3)) {
			User user = StorageHandler.getUser(userName,
					NewUserActivity.getContext());
			if (userName.equals(user.getUserName())) {
				response = "userExist";
				return response;
			} else {
				StorageHandler.storeUser(new User(userName, password));
				response = "ok";
				return response;
			}
		} else {
			response = "wrongInData"; // User filled in no user name or too
										// short password
			return response;
		}
	}

	/**
	 * Removes the user that is logged in.
	 */
	public static void removeUser() {
		StorageHandler.removeUser(session);

	}

	/**
	 * Returns a list with the books that the user that is logged in have
	 * added
	 * 
	 * @return ArrayList with books.
	 */
	public static ArrayList<Book> getMyBooks() {

		ArrayList<Book> list = StorageHandler.getMyBooks(session);

		return list;
	}

	/**
	 * Removes all users in the database, fore administrator.
	 */
	public static void removeAllUsers() {

		StorageHandler.removeAllUsers();
	}
}
